package cn.innosmart.aq.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;

import com.tutk.p2p.ConnectionEntity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.innosmart.aq.R;
import cn.innosmart.aq.adapter.AquariumListAdapter;
import cn.innosmart.aq.bean.AlarmConditionBean;
import cn.innosmart.aq.bean.AquariumBean;
import cn.innosmart.aq.bean.DeviceBean;
import cn.innosmart.aq.customize.CustomsizeDialog;
import cn.innosmart.aq.customize.InputDialog;
import cn.innosmart.aq.manager.PlaceManager;
import cn.innosmart.aq.manager.RuleManager;
import cn.innosmart.aq.manager.SceneManager;
import cn.innosmart.aq.manager.ScheduleManager;
import cn.innosmart.aq.util.DeviceConstant;
import cn.innosmart.aq.util.SystemConstant;
import cn.innosmart.aq.view.activity.BoxDetailActivity;
import cn.innosmart.aq.view.activity.FullscreenMonitoringActivity;
import cn.innosmart.aq.view.activity.PlaceModifyActivity;

/**
 * 所有鱼缸的Fragment
 */
public class BoxDetailAllFragment extends BaseFragment {
    private final int DATACHANGE = 1;
    private View view;
    private RelativeLayout rlAll;
    private ListView lvAquariums;
    private AquariumListAdapter aquariumListAdapter;
    private ConnectionEntity connectionEntity;
    private Menu menus;
    private boolean isModify = false;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_add_aquarium:
                    break;
                case R.id.action_edit_aquarium:
                    //进入修改模式
                    isModify = !isModify;
                    if (isModify) {
                        menuItem.setTitle(getString(R.string.action_exit_edit));
                    } else {
                        menuItem.setTitle(getString(R.string.edit));
                    }
                    aquariumListAdapter.startModify(isModify);
                    break;
                case R.id.action_message:
                    //原来的IM即使聊天入口
//                    Intent intents = new Intent(getActivity(), FriendActivity.class);
//                    getActivity().startActivity(intents);
//                    getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
                    break;
            }
            return true;
        }
    };
    /**
     * 设置Toolbar
     */
    private Toolbar toolbar;
    private boolean isRemove;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    aquariumListAdapter.notifyDataSetChanged();
                    if (SystemConstant.aquariumList.size() == 0) {
                        //没有鱼缸弹出遮盖层
                        showInfo();
                    } else {
                        hideInfo();
                    }
                    break;
                case DATACHANGE:
                    aquariumListAdapter.notifyDataSetChanged();
                    break;
            }
        }
    };
    public View.OnClickListener OnClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_addlayout:
                    //添加鱼缸
                    Intent intent = new Intent(getActivity(), PlaceModifyActivity.class);
                    intent.putExtra("UID", connectionEntity.getUid());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                    break;
                case R.id.modify_setting:
                    //修改鱼缸名称
                    int position = (int) v.getTag();
                    AquariumBean aquariumBean = SystemConstant.aquariumList.get(position);
                    showModifyDevice(aquariumBean);
                    break;
                case R.id.modify_delete:
                    //删除鱼缸名称
                    int position2 = (int) v.getTag();
                    AquariumBean aquariumBean2 = SystemConstant.aquariumList.get(position2);
                    removeAlertDialog(aquariumBean2);
                    break;
                case R.id.ll_aquarium:
                    int position3 = (int) v.getTag();
                    AquariumBean aquariumBean3 = SystemConstant.aquariumList.get(position3);
                    if (!isModify) {
                        Message msg = BoxDetailActivity.getHandler().obtainMessage();
                        msg.what = 1;
                        msg.obj = aquariumBean3;
                        msg.arg1 = position3;
                        BoxDetailActivity.getHandler().sendMessage(msg);
                    }
                    break;
            }
        }
    };

    public void setConnectionEntity(ConnectionEntity connectionEntity) {
        this.connectionEntity = connectionEntity;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_all, container, false);
        rlAll = (RelativeLayout) view.findViewById(R.id.rl_all);
        lvAquariums = (ListView) view.findViewById(R.id.lv_aquariums);
        aquariumListAdapter = new AquariumListAdapter(getActivity(), OnClickListener);
        lvAquariums.setAdapter(aquariumListAdapter);
        setBar();

        //Intent intent = new Intent(getActivity(), FullscreenMonitoringActivity.class);
        //startActivity(intent);
        //getActivity().overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

        return view;
    }

    @Override
    public void onResume() {
        if (SystemConstant.aquariumList != null && SystemConstant.aquariumList.size() == 0) {
            //没有鱼缸弹出遮盖层
            showInfo();
        } else {
            hideInfo();
        }
        getActivity().invalidateOptionsMenu();
        //判断鱼缸是否报警
        for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
            AquariumBean aquariumBean = SystemConstant.aquariumList.get(i);
            ArrayList<String> devices = aquariumBean.getDeivices();
            aquariumBean.setIsAlarm(false);
            for (int j = 0; j < devices.size(); j++) {
                DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(devices.get(j));

                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_METER_WATT) {
                    continue;
                }

                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                    int alarmType = 0;

                    String slist[] = deviceBean.getAddress().split("\\/");
                    String wattDeviceBeanAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 50 + "/" + slist[5] + "/" + 2;
                    DeviceBean wattDeviceBean = SystemConstant.deviceBeanHashMap.get(wattDeviceBeanAddress);

                    if (wattDeviceBean != null) {
                        AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
                        if (alarmConditionBean != null) {
                            if (wattDeviceBean.oldAlarmType == -1) {
                                //first
                                if (deviceBean != null && deviceBean.getSensorvalue() == 255 && wattDeviceBean.getSensorvalue() < 10 && wattDeviceBean.getSensorvalue() >= 0) {
                                    //to check switch
                                    wattDeviceBean.oldAlarmType = 8;
                                } else {
                                    wattDeviceBean.oldAlarmType = 0;
                                }
                            }

                            if (wattDeviceBean.oldAlarmType > 0) {
                                alarmType = wattDeviceBean.oldAlarmType; //low watt exception
                            } else if (wattDeviceBean.oldAlarmType == 0) {
                                alarmType = wattDeviceBean.oldAlarmType; //low watt exception
                            }
                        }
                    }

                    System.out.println("watt exception 1, alarmType=" + alarmType);
                    aquariumBean.setIsAlarm(alarmType > 0);

                } else {
                    if (deviceBean.isAlarm())
                        System.out.println("non-watt exception 1, " + deviceBean.getName());

                    aquariumBean.setIsAlarm(deviceBean.isAlarm());
                }
            }
        }
        //刷新界面
        aquariumListAdapter.notifyDataSetChanged();
        super.onResume();
    }

    //弹出提示层
    private void showInfo() {
        rlAll.setVisibility(View.VISIBLE);
    }

    //隐藏提示层
    private void hideInfo() {
        rlAll.setVisibility(View.GONE);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_boxdetail_all, menu);
        if (SystemConstant.aquariumList.size() == 0) {
            menu.findItem(R.id.action_edit_aquarium).setVisible(false);
        }
        menus = menu;
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        //根据鱼缸的数量 如果没有鱼缸 则编辑菜单不显示
        if (SystemConstant.aquariumList.size() != 0) {
            menu.findItem(R.id.action_edit_aquarium).setVisible(true);
        } else {
            menu.findItem(R.id.action_edit_aquarium).setVisible(false);
        }
        //根据编辑状态显示
        if (isModify) {
            menus.findItem(R.id.action_edit_aquarium).setTitle(getString(R.string.action_exit_edit));
        } else {
            menus.findItem(R.id.action_edit_aquarium).setTitle(getString(R.string.edit));
        }
        super.onPrepareOptionsMenu(menu);
    }

    private void setBar() {
        toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }

    /**
     * 显示修改设备的对话框
     *
     * @param aquariumBean 所在鱼缸
     */
    private void showModifyDevice(final AquariumBean aquariumBean) {
        final EditText etName;
        final InputDialog deviceNameModifyDialog = new InputDialog(getActivity());
        etName = (EditText) deviceNameModifyDialog.findViewById(R.id.et_name);
        etName.setText(aquariumBean.getTitle());
        deviceNameModifyDialog.setHint(getString(R.string.title));
        deviceNameModifyDialog.setTitle(getActivity().getString(R.string.fragment_all_modify_device_title));
        deviceNameModifyDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String name = etName.getText().toString().trim();
                if (TextUtils.isEmpty(name)) {
                    showToast(getActivity().getString(R.string.fragment_all_aquarium_name_can_not_empty));
                    return;
                }
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("id", aquariumBean.getId());
                    jsonObject.put("title", name);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                showLoadingDialog(getActivity());
                //发送更新的指令
                PlaceManager.getInstance().Update(connectionEntity, jsonObject.toString(), new PlaceManager.UpdateCallBack() {
                    @Override
                    public void onUpdateResponseCallBack(int ret) {
                        if (ret == 0) {
                            aquariumBean.setTitle(name);
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            mHandler.sendEmptyMessage(DATACHANGE);
                        } else {
                            hideLoadingDialog();
                            deviceNameModifyDialog.dismiss();
                            showToast(getActivity().getString(R.string.fragment_all_modify_aquarium_failed));
                        }
                    }
                });
            }
        });
        deviceNameModifyDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deviceNameModifyDialog.dismiss();
            }
        });
        deviceNameModifyDialog.show();
    }

    /**
     * 删除设备的提示对话框
     *
     * @param aquariumBean 所在的鱼缸
     */
    private void removeAlertDialog(final AquariumBean aquariumBean) {
        final CustomsizeDialog infoDialog = new CustomsizeDialog(getActivity());
        infoDialog.setTitle(getActivity().getString(R.string.dialog_title_alert));
        infoDialog.setContent(String.format(getString(R.string.dialog_content_delete_sure), aquariumBean.getTitle()));
        infoDialog.setNegativeButton(getActivity().getString(R.string.cancel), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoDialog.dismiss();
            }
        });
        infoDialog.setPositiveButton(getActivity().getString(R.string.sure), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                infoDialog.dismiss();
                Message msg = BoxDetailActivity.getHandler().obtainMessage();
                msg.obj = getActivity().getString(R.string.dialog_progress_loading);
                msg.what = 11;
                BoxDetailActivity.getHandler().sendMessage(msg);
                removeAquarium(aquariumBean);
            }
        });
        infoDialog.show();
    }

    //删除鱼缸
    private void removeAquarium(final AquariumBean aquariumBean) {
        isRemove = true;
        JSONObject ruleRoot = new JSONObject();
        JSONArray ruleParams = new JSONArray();
        for (int i = 0; i < aquariumBean.getRuleList().size(); i++) {
            ruleParams.put(aquariumBean.getRuleList().get(i).getId());
        }
        if (ruleParams.length() != 0) {
            try {
                ruleRoot.put("ids", ruleParams);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //删除其中的规则
            RuleManager.getInstance().Remove(connectionEntity, ruleRoot.toString(), new RuleManager.RemoveCallBack() {
                @Override
                public void onRemoveResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        aquariumBean.getRuleList().clear();
                    } else {
                        isRemove = false;
                    }
                }
            });
        }
        JSONObject scheduleRoot = new JSONObject();
        JSONArray scheduleParams = new JSONArray();
        for (int i = 0; i < aquariumBean.getScheduleList().size(); i++) {
            scheduleParams.put(aquariumBean.getScheduleList().get(i).getId());
        }
        if (scheduleParams.length() != 0) {
            try {
                scheduleRoot.put("ids", scheduleParams);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //删除其中的排程
            ScheduleManager.getInstance().Remove(connectionEntity, scheduleRoot.toString(), new ScheduleManager.RemoveCallBack() {
                @Override
                public void onRemoveResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        aquariumBean.getScheduleList().clear();
                    } else {
                        isRemove = false;
                    }
                }
            });
        }
        JSONObject sceneRoot = new JSONObject();
        JSONArray sceneParams = new JSONArray();
        for (int i = 0; i < aquariumBean.getSceneList().size(); i++) {
            sceneParams.put(aquariumBean.getSceneList().get(i).getId());
        }
        if (sceneParams.length() != 0) {
            try {
                sceneRoot.put("ids", sceneParams);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //删除其中的场景
            SceneManager.getInstance().Remove(connectionEntity, sceneRoot.toString(), new SceneManager.RemoveCallBack() {
                @Override
                public void onRemoveResponseCallBack(int ret, String ruleid) {
                    if (ret == 0) {
                        aquariumBean.getSceneList().clear();
                    } else {
                        isRemove = false;
                    }
                    if (isRemove) {
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                JSONObject jParams = new JSONObject();
                                try {
                                    jParams.put("id", aquariumBean.getId());
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                                //删除鱼缸指令
                                PlaceManager.getInstance().Remove(connectionEntity, jParams.toString(), new PlaceManager.RemoveCallBack() {
                                    @Override
                                    public void onRemoveResponseCallBack(int ret) {
                                        if (ret == 0) {
                                            String id = aquariumBean.getId();
                                            for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
                                                if (id.equals(SystemConstant.aquariumList.get(i).getId()))
                                                    SystemConstant.aquariumList.remove(i);
                                            }
                                            mHandler.sendEmptyMessage(0);
                                            BoxDetailActivity.getHandler().sendEmptyMessage(2);
                                        } else {
                                            showToast(getActivity().getString(R.string.delete_failed));
                                            mHandler.sendEmptyMessage(0);
                                            BoxDetailActivity.getHandler().sendEmptyMessage(2);
                                        }
                                    }
                                });
                            }
                        }).start();
                    } else {
                        showToast(getActivity().getString(R.string.delete_failed));
                        mHandler.sendEmptyMessage(0);
                        BoxDetailActivity.getHandler().sendEmptyMessage(2);
                    }
                }
            });
        } else {
            JSONObject jParams = new JSONObject();
            try {
                jParams.put("id", aquariumBean.getId());
            } catch (JSONException e) {
                e.printStackTrace();
            }
            //删除鱼缸指令
            PlaceManager.getInstance().Remove(connectionEntity, jParams.toString(), new PlaceManager.RemoveCallBack() {
                @Override
                public void onRemoveResponseCallBack(int ret) {
                    if (ret == 0) {
                        String id = aquariumBean.getId();
                        for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
                            if (id.equals(SystemConstant.aquariumList.get(i).getId()))
                                SystemConstant.aquariumList.remove(i);
                        }
                        mHandler.sendEmptyMessage(0);
                        BoxDetailActivity.getHandler().sendEmptyMessage(2);
                    } else {
                        showToast(getActivity().getString(R.string.delete_failed));
                        mHandler.sendEmptyMessage(0);
                        BoxDetailActivity.getHandler().sendEmptyMessage(2);
                    }
                }
            });
        }
    }

    /**
     * 更新数据
     */
    public void updateData() {
        if (SystemConstant.aquariumList == null) {
            return;
        }
        for (int i = 0; i < SystemConstant.aquariumList.size(); i++) {
            AquariumBean aquariumBean = SystemConstant.aquariumList.get(i);
            ArrayList<String> devices = aquariumBean.getDeivices();
            aquariumBean.setIsAlarm(false);

            for (int j = 0; j < devices.size(); j++) {
                DeviceBean deviceBean = SystemConstant.deviceBeanHashMap.get(devices.get(j));

                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_METER_WATT) {
                    continue;
                }
                if (deviceBean.getFunctype() == DeviceConstant.FUNCTYPE_SWITCH) {
                    int alarmType = 0;

                    String slist[] = deviceBean.getAddress().split("\\/");
                    String wattDeviceBeanAddress = slist[0] + "//" + slist[2] + "/" + slist[3] + "/" + 50 + "/" + slist[5] + "/" + 2;
                    DeviceBean wattDeviceBean = SystemConstant.deviceBeanHashMap.get(wattDeviceBeanAddress);

                    if (wattDeviceBean != null) {
                        AlarmConditionBean alarmConditionBean = DeviceConstant.alarmConditionBeanHashMap.get(wattDeviceBean.getAddress());
                        if (alarmConditionBean != null) {
                            if (wattDeviceBean.oldAlarmType == -1) {
                                //first
                                if (deviceBean != null && deviceBean.getSensorvalue() == 255 && wattDeviceBean.getSensorvalue() < 10 && wattDeviceBean.getSensorvalue() >= 0) {
                                    //to check switch
                                    wattDeviceBean.oldAlarmType = 8;
                                } else {
                                    wattDeviceBean.oldAlarmType = 0;
                                }
                            }

                            if (wattDeviceBean.oldAlarmType > 0) {
                                alarmType = wattDeviceBean.oldAlarmType; //low watt exception
                            } else if (wattDeviceBean.oldAlarmType == 0) {
                                alarmType = wattDeviceBean.oldAlarmType; //low watt exception
                            }
                        }
                    }
                    System.out.println("watt exception 2, alarmType=" + alarmType);
                    aquariumBean.setIsAlarm(alarmType > 0);

                } else {
                    if (deviceBean.isAlarm())
                        System.out.println("non-watt exception 2, " + deviceBean.getName());

                    aquariumBean.setIsAlarm(deviceBean.isAlarm());
                }
            }
        }
        aquariumListAdapter.notifyDataSetChanged();
    }
}
